package com.example.practice.class04;

/**
 * @Date 2022/9/12
 * @Author Jonathan
 * @link {https://leetcode.cn/problems/candy/}
 */
public class Code05_Candy {


    public static void main(String[] args) {
        //int[] nums = new int[]{1, 2, 87, 87, 87, 2, 1};
        int[] nums = new int[]{1, 0, 2};
        final Code05_Candy candy = new Code05_Candy();
        final int candy1 = candy.candy(nums);
        System.out.println(candy1);
    }


    public int candy(int[] ratings) {
        if (ratings == null || ratings.length == 0) {
            return 0;
        }
        final int N = ratings.length;
        int[] leftCandy = new int[N];
        int[] rightCandy = new int[N];
        leftCandy[0] = 1;
        rightCandy[N - 1] = 1;
        for (int i = 1; i < N; i++) {
            if (ratings[i - 1] < ratings[i]) {
                leftCandy[i] = leftCandy[i - 1] + 1;
            } else {
                leftCandy[i] = 1;
            }
        }

        // 扣边界
        for (int i = N - 2; i >= 0; i--) {
            if (ratings[i] > ratings[i + 1]) {
                rightCandy[i] = rightCandy[i + 1] + 1;
            } else {
                rightCandy[i] = 1;
            }
        }
        int ans = 0;
        for (int i = 0; i < N; i++) {
            ans += Math.max(leftCandy[i], rightCandy[i]);
        }
        return ans;
    }
}
